function dumbLocalStorageAgent() {
  return {
    get() {
      return null
    },

    set(_: Record<string, string>) {},
  }
}

function getLocalStorageKey(name: string) {
  return `inula-code-${name}`
}
export interface LocalStorageAgent {
  get: () => Record<string, string> | null
  set: (files: Record<string, string>) => void
}
export function createLocalStorageAgent(name: string, enableStorage?: boolean): LocalStorageAgent {
  if (enableStorage === false)
    return dumbLocalStorageAgent()

  return {
    get() {
      const files = localStorage.getItem(getLocalStorageKey(name)) ?? ''
      if (files) {
        try {
          return JSON.parse(files) as Record<string, string>
        }
        catch (e) {
          localStorage.removeItem(getLocalStorageKey(name))
        }
      }
      return null
    },

    set(value: Record<string, string>) {
      localStorage.setItem(getLocalStorageKey(name), JSON.stringify(value))
    },
  }
}
